package application;

import javafx.beans.property.SimpleStringProperty;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

public class Operator {

    public void pingStart(Bean bean) {
        try {
            Runtime r = Runtime.getRuntime();
            Process process = null;

            if (Objects.nonNull(bean.getIp()) && !bean.getIp().isEmpty()) {

                if (Objects.nonNull(bean.getPort()) && !bean.getPort().isEmpty()) {
                    process = r.exec("utils/tcping64.exe " + bean.getIp().trim() + " " + bean.getPort().trim());
                } else {
                    process = r.exec("utils/tcping64.exe " + bean.getIp().trim());
                }

                InputStream inputStream = process.getInputStream();
                byte[] bytes = new byte[1024];
                int i = 0;

                while (inputStream.read(bytes) > 0) {
                    String result = new String(bytes, "GBK");
                    if (result.startsWith("Probing") && result.contains("Port is open")) {
                        i++;
                    }
                }

                if (i > 0) {
                    bean.setStatus(new SimpleStringProperty("YES"));
                    bean.setRate(new SimpleStringProperty((i * 100 / 4) + "%"));
                } else {
                    bean.setStatus(new SimpleStringProperty("NO"));
                    bean.setRate(new SimpleStringProperty("0%"));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
